package com.yztstudy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yztstudy.dto.Result;
import com.yztstudy.dto.ScrollResult;
import com.yztstudy.dto.UserDTO;
import com.yztstudy.entity.Blog;
import com.yztstudy.entity.Follow;
import com.yztstudy.entity.User;
import com.yztstudy.mapper.BlogMapper;
import com.yztstudy.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yztstudy.service.IFollowService;
import com.yztstudy.service.IUserService;
import com.yztstudy.utils.RedisConstants;
import com.yztstudy.utils.SystemConstants;
import com.yztstudy.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;


    /**
     * TODO 根据ID查询已经发表的博客
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        // TODO 1.查询blog
        Blog blog = getById(id);
        if (blog == null)
        {
            return Result.fail("blog不存在!");
        }

        // TODO 2.查询与这个blog相关的用户
        Long userId = blog.getUserId(); //获取用户的ID
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        // TODO 3.查询用户是否被点赞了
        isBlogLiked(blog);

        return Result.ok(blog);
    }


    /**
     * TODO 查询用户是否点赞
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        // TODO 1.获取当前登录用户
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null) //用户未登录，无需查询是否点赞
        {
            return;
        }

        // TODO 2.判断当前用户点了赞没
        Long userId = userDTO.getId();
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), userId.toString());
        blog.setIsLike(score != null ? true : false); //如果返回值为true，则点了赞
    }


    /**
     * TODO 查询热点博客,前端首页展示
     * @param current 分页的页数
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // TODO 1.根据用户查询
        Page<Blog> page = query().orderByDesc("liked").page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));

        // TODO 2.获取当前页面的数据
        List<Blog> records = page.getRecords();

        // TODO 3.查询用户
        records.forEach(blog -> {

            // 展示写这个博客的人的信息
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());

            // 查询用户是否被点赞了
            isBlogLiked(blog);
        });

        return Result.ok(records);
    }


    /**
     * TODO 用户点赞功能
     * @param id 当前博客的ID
     * @return
     */
    @Override
    public Result likeBlog(Long id) {

        // TODO 1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();

        // TODO 2.判断当前用户点了赞没
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());

        // TODO 3.如果没有点过赞，即可以点赞，点赞数+1，加入到redis的zset集合
        if (score == null)
        {
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess)
            {
                stringRedisTemplate.opsForZSet().add(RedisConstants.BLOG_LIKED_KEY + id, userId.toString(), System.currentTimeMillis());
            }
        }

        // TODO 4.如果已经点了赞，则取消点赞，点赞数-1，从redis的zset集合中移除
        else {
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess)
            {
                stringRedisTemplate.opsForZSet().remove(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
            }
        }

        return Result.ok();
    }


    /**
     * TODO 根据博客的ID查询点赞的人(前5个) zrange key 0 4
     * @param id 博客的ID
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {

        // TODO 1.查询出top5的用户
        Set<String> Top5ID = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4); //返回的全是userId
        if (Top5ID == null || Top5ID.isEmpty())
        {
            return Result.ok(Collections.emptyList());
        }

        // TODO 2.解析成为用户ID
        List<Long> IDs = Top5ID.stream().map(Long::valueOf).collect(Collectors.toList());

        // TODO 3.根据ID查询用户
        String idStr = StrUtil.join(",", IDs);
        List<User> users = userService.query().in("id", IDs).last("ORDER BY FIELD(id, " + idStr + ")").list();

        // TODO 4.信息屏蔽
        List<UserDTO> userDTOs = users.stream().map(user -> {
            return BeanUtil.copyProperties(user, UserDTO.class);
        }).collect(Collectors.toList());

        return Result.ok(userDTOs);
    }


    /**
     * TODO 查询这个博主的所有笔记
     * @param current 当前的分页数量
     * @param id 用户的ID
     * @return
     */
    @Override
    public Result queryOtherBlog(Integer current, Long id) {

        // TODO 1.根据用户查询
        Page<Blog> page = query().eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));

        // TODO 2.获取本页数据
        List<Blog> records = page.getRecords();

        return Result.ok(records);
    }


    /**
     * TODO 查询自己发表过的笔记
     * @param current
     * @return
     */
    @Override
    public Result queryMyBlog(Integer current) {

        // TODO 1.获取登录用户
        UserDTO user = UserHolder.getUser();

        // TODO 2.根据用户查询
        Page<Blog> page = query().eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));

        // TODO 3.获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }


    /**
     *  TODO 保存用户发表过的博客
     * @param blog 博客
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {

        // TODO 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());

        // TODO 2.保存探店博文
        boolean isSave = save(blog);
        if (!isSave)
        {
            return Result.fail("新增失败!");
        }

        // TODO 3.查询笔记发布作者的所有粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        for (Follow follow : follows)
        {
            Long fansId = follow.getUserId();
            stringRedisTemplate.opsForZSet().add(RedisConstants.FEED_KEY + fansId, blog.getId().toString(), System.currentTimeMillis()); //推送，一个用户一个收件箱
        }

        // TODO 4.返回id
        return Result.ok(blog.getId());

    }


    /**
     * TODO 滚动分页查询(查询当前用户所关注的人，发的笔记)
     * @param max 上一次查询的最小时间戳
     * @param offset 偏移量
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {

        // TODO 1.获取当前用户
        Long userId = UserHolder.getUser().getId();

        // TODO 2.查询收件箱(score从大到小查询)
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(RedisConstants.FEED_KEY + userId.toString(), 0, max, offset, 3);
        if (typedTuples == null || typedTuples.isEmpty())
        {
            return Result.ok(Collections.emptyList());
        }

        // TODO 3.解析数据,解析里面的blogID,minTime,offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0L; //最小时间戳
        int count = 1; //最小时间戳的计数器
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples)
        {
            String idStr = tuple.getValue(); //获取id(博客的ID)
            ids.add(Long.valueOf(idStr));

            long time = tuple.getScore().longValue(); //获取当前分数(时间戳,最小的那个,也就是最后的那个)
            if (time == minTime)
            {
                count++;
            } else {
                minTime = time;
                count = 1;
            }
        }

        // TODO 4.根据ID查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        for (Blog blog : blogs)
        {
            // TODO 5.查询与这个blog相关的用户
            Long userID = blog.getUserId(); //获取用户的ID
            User user = userService.getById(userID);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());

            // TODO 6.查询用户是否被点赞了
            isBlogLiked(blog);
        }

        // TODO 7.封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(count);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }
}
